#-*- coding: utf-8 -*-

from utils.common import logable, trace_method, NDW_DEBUG, NDW_INFO

__author__ = 'sysprog'

@logable
class Analyzer(object):
    def __new__(cls, level, *args, **kwargs):
        instance = super(Analyzer, cls).__new__(cls)

        instance.log(NDW_INFO, "Create analyzer with level = %d", level)

        instance.__level = level

        if level == 4:
            instance.__active_analyzers = ["control31", "control32"]
        elif level == 3:
            instance.__active_analyzers = ["control31", "control32",
                                           "control33", "control34",
                                           "control35", "control37"]

        instance.log(NDW_INFO, "Need to apply following controls: %s", instance.__active_analyzers)
        return instance

    @property
    def controls(self):
        from analyze.common.controls import controls
        from collections import OrderedDict
        dct = {x: controls[x] for x in self.__active_analyzers}
        return OrderedDict(sorted(dct.items(), key=lambda t: t[0]))

    @staticmethod
    def __get_enabled(level):
        res = {}
        if level <= 4:
            res["enable4"] = True
        if level <= 3:
            res["enable3"] = True
        if level <= 2:
            res["enable2"] = True
        if level <= 1:
            res["enable1"] = True

        return res

    @trace_method
    def analyze(self, **kwargs):
        import os
        import codecs
        from django.template import Context
        from utils.view import get_template

        config = kwargs["config"]
        path_to_report_dir = config.get("Common", "report_dir")

        for a_name in self.controls:
            self.log(NDW_INFO, "start to analyze '%s'", a_name)

            report_name = os.path.join(path_to_report_dir, a_name + ".html")
            context_dict = {"title": u"НДВизард", }

            template = get_template(a_name + ".html")

            context_dict.update(self.controls[a_name](context_dict, level=self.__level, **kwargs))

            context_dict.update(Analyzer.__get_enabled(self.__level))

            cntx = Context(context_dict)

            html = template.render(cntx)

            with codecs.open(report_name, "w", encoding="utf-8") as report:
                report.write(html)
